<?php

/*
 * B端操作功能模块
 * 功能：优惠劵
 */

namespace Home\Controller;

use Think\B_Controller;

class CouponController extends B_Controller {

    public function __construct() {
        parent::__construct();
        $this->coupon = D('Coupon', 'Logic');
    }

    public function index() {
        $status = (int) $_GET['status'];
        $type = (int) $_GET['type'];
        $this->assign('status', $status);
        $this->assign('type', $type);
        $store_id = (int)$_GET['store_id'];
        if(!in_array($store_id,$this->store_id)){
            $store_id = $this->store_id;
        }
        if ($status == 2) {
            $status = 0;
            $arr['status'] = $status;
        } elseif ($status == 1) {
            $arr['status'] = $status;
        }
        if ($type == 1) {
            $arr['type_name'] = '折扣券';
        } elseif ($type == 2) {
            $arr['type_name'] = '现金券';
        }
        $arr['store_id'] = $store_id;
        $coupons = $this->coupon->lists($arr);
        foreach($coupons as $k=>$v){
            if($v['status']==1){
                    if($v['start_time']<time() && $v['end_date']>time()){ 
                        $coupons[$k]['status'] = '发放中';
                    }elseif($v['start_time']>time()){
                        $coupons[$k]['status'] =  '未开始';
                    }else{
                        $coupons[$k]['status'] =  '已结束';
                    }
            }else{
                $coupons[$k]['status'] = '草稿';
            }
        }
        $this->assign('coupon', $coupons);
        $this->assign('store_id', $store_id);
        $this->display('coupon');
    }

    public function appendIndex() {
        $status = (int) $_GET['status'];
        $type = (int) $_GET['type'];
        $store_id = (int)$_GET['store_id'];
        $start = (int) $_GET['start'];
        if(!in_array($store_id,$this->store_id)){
            $store_id = $this->store_id;
        }
        if ($status == 2) {
            $status = 0;
            $arr['status'] = $status;
        } elseif ($status == 1) {
            $arr['status'] = $status;
        }
        if ($type == 1) {
            $arr['type_name'] = '折扣券';
        } elseif ($type == 2) {
            $arr['type_name'] = '现金券';
        }
        $arr['store_id'] = $store_id;
        $coupons = $this->coupon->lists($arr, $start);

        if (count($coupons) > 0) {
            foreach($coupons as $k=>$v){
                if($v['status']==1){
                        if($v['start_time']<time() && $v['end_date']>time()){ 
                            $coupons[$k]['status'] = '发放中';
                        }elseif($v['start_time']>time()){
                            $coupons[$k]['status'] =  '未开始';
                        }else{
                            $coupons[$k]['status'] =  '已结束';
                        }
                }else{
                    $coupons[$k]['status'] = '草稿';
                }
            }

            exit(json_encode($coupons));
        }
        exit('false');
    }

    public function create() {
        if (empty($this->store)) {
            redirect('/home/store/');
        }
        $coupon_id = (int) $_GET['coupon_id'];
        if ($coupon_id > 0) {
            $coupon = $this->coupon->getHuiById($coupon_id);
            if (!in_array($coupon['store_id'] , $this->store_id)) {
                $this->_msg('非法操作！');
            }
        }
        if ((int) $_GET['num']) {
            $this->assign('num', (int) $_GET['num']);
        }
        $this->assign('coupon', $coupon);
        $this->display('create');
    }

    public function submit() {
        if ((int) $_POST['is_action']) {
            $data['is_action'] = (int) $_POST['is_action'];
            $data['store_id'] = (int)$_POST['store'];
            $data['name'] = $_POST['coupon_name'];
            $data['type_name'] = $_POST['type_name'];
            $data['content'] = $_POST['coupon_content'];
            $data['num'] = (int) $_POST['coupon_num'];
            $data['style'] = (int) $_POST['coupon_style'];
            $data['end_date'] = strtotime($_POST['coupon_end_date']) + 86399;
            $data['start_time'] = strtotime($_POST['coupon_start_time']);
            $data['end_time'] = strtotime($_POST['coupon_end_time']) + 86399;
            $data['intro'] = str_replace("\n",'',$_POST['coupon_intro']);
            $data['condition'] = (int) $_POST['coupon_condition'];
        } else {
            $data['is_action'] = 0;
            $coupon_id = (int) $_POST['coupon_id'];
            $data['store_id'] = (int)$_POST['store'];
            $data['name'] = $_POST['name'];
            $data['type_name'] = $_POST['type_name'];
            $data['content'] = $_POST['content'];
            $data['num'] = (int) $_POST['num'];
            $data['style'] = (int) $_POST['style'];
            $data['end_date'] = strtotime($_POST['end_date']) + 86399;
            $data['start_time'] = strtotime($_POST['start_time']);
            $data['end_time'] = strtotime($_POST['end_time']) + 86399;
            $data['intro'] = str_replace("\n",'',$_POST['intro']);
            $data['condition'] = (int) $_POST['condition'];
        }
        if (!in_array($data['store_id'],$this->store_id)) {
            $this->_msg('_HAVE_NO_LEGAL_POWER_');
        }
        if (strlen($data['name']) < 1 ||
                strlen($data['type_name']) < 1 ||
                strlen($data['content']) < 1 ||
                $data['num'] > 100 ||
                $data['num']==0  ||
                $data['start_time'] == FALSE ||
                $data['end_time'] == FALSE   ||
                $data['end_date'] == FALSE
        ){
            $this->_msg('_SYSTEM_ERROR_');
        }
        if ($data['style'] > 0) {
            $image = $this->images($data);
            $data['style'] = $image;
        }
        if ($coupon_id != '' && $coupon_id > 0) {
            $_coupon = $this->coupon->getHuiById($coupon_id);
            if(!in_array($_coupon['store_id'],$this->store_id)){
                $this->_msg('_HAVE_NO_LEGAL_POWER_');
            }
            $re = $this->coupon->updateHui($coupon_id, $data);
        } else {
            $data['create_time'] = time();
            $data['count'] = 0;
            if((int)$_POST['is_action']==1){
                $data['status']=1;
            }
            $coupon_id = $this->coupon->insertHui($data);
        }
        if((int)$_POST['is_action']==1){
            if($coupon_id>1){
                echo (int)$_POST['t'];
                exit;
            }else{
                echo 0;
                exit;
            }
            
        }
        if ($_POST['caogao'] == '保存草稿') {
            redirect('/home/coupon');
        }
        redirect("/home/coupon/peview?coupon_id=$coupon_id");
    }

    public function peview() {
        $coupon_id = (int) $_GET['coupon_id'];
        $_coupon = $this->coupon->getHuiById($coupon_id);
        if(!in_array($_coupon['store_id'],$this->store_id)){
            $this->_msg('非法操作！');
        }
        $st = new \Home\Logic\StoreLogic();
        $store = $st->getStore($_coupon['store_id']);
        $this->assign('store',$store);
        $this->assign('coupon', $_coupon);
        $this->display('peview');
    }

    public function ajax() {
        $num = (int) $_GET['num'];
        echo $num;
    }

    public function release() {
        $coupon_id = (int) $_GET['coupon_id'];
        $status = array('status' => 1);
        $_coupon = $this->coupon->getHuiById($coupon_id);
        if(!in_array($_coupon['store_id'],$this->store_id)){
            $this->_msg('非法操作！');
        }
        $re = $this->coupon->updateHui($coupon_id, $status);
        if ($re) {
            redirect('/home/coupon');
        } else {
            $this->_msg('_SYSTEM_ERROR_');
        }
    }

    public function images($coupon) {
        $time = date("Y-m-d", $coupon['end_time']);
        $content = $coupon['content'];
        $condition = $coupon['condition'];
        if ($coupon['style'] == 1) {
            if ($coupon['type_name'] == '折扣券') {
                if ($condition == 0) {
                    $path = './public/images/coupon1.png';
                } else {
                    $path = './public/images/coupon2.png';
                }
            } elseif ($coupon['type_name'] == "现金券") {
                if ($condition == 0) {
                    $path = './public/images/coupon5.png';
                } else {
                    $path = './public/images/coupon6.png';
                }
            } elseif ($coupon['type_name'] == '体验券') {
                if ($condition == 0) {
                    $path = './public/images/coupon3.png';
                } else {
                    $path = './public/images/coupon4.png';
                }
            }
        }
        $image = new \Think\Image();
        $date = date("Y-m-d", time());
        $file = "./public/upload/$date";
        if (!is_dir($file)) {
            mkdir($file, 0777, true);
        }
        $imagename = "./public/upload/$date/" . time() . $this->store['user_id'] . '.png';
        $font = './public/font/msyhbd.ttc';
        $red = '#ff0000';
        $white = '#ffffff';
        $size = 30;
        $time = date("Y-m-d", $coupon['end_time']).'前到店使用';
        $conlocate_time = array(-40,105);
        if($content>999){
            $locate=array(35,60); 
            $conlocate = array(-10,20);
        }elseif($content<=999){
            if($content>99){
                $locate=array(50,60);
                $conlocate = array(-10,20); 
            }elseif($content>9){
                $locate=array(60,60);
                $conlocate = array(-10,20);
            }else{
                $locate=array(70,60);
                $conlocate = array(-10,20);
            }    
        }
        
        if ($condition == 0) {
            $image->open($path)->text($content, $font, $size, $white, \Think\Image::IMAGE_WATER_NORTHWEST,$locate)
                    ->text($time, $font, 17, $white, \Think\Image::IMAGE_WATER_NORTH, $conlocate_time)
                    ->save($imagename);
        } else {
            $condition='满'.$condition.'元可使用';
            $image->open($path)->text($content, $font, $size, $white, \Think\Image::IMAGE_WATER_NORTHWEST, $locate)
                    ->text($condition, $font, 20, $white, \Think\Image::IMAGE_WATER_NORTH, $conlocate)
                    ->text($time, $font, 17, $white, \Think\Image::IMAGE_WATER_NORTH, $conlocate_time)
                    ->save($imagename);
        }   
        $imagename = str_replace("./", "/", $imagename);
        return $imagename;
    }

    public function image($path, $coupon) {
        $name = $coupon['name'];
        $time = date("Y-m-d", $coupon['end_time']);
        $content = $coupon['content'];

        $image = new \Think\Image();
        $date = date("Y-m-d", time());
        $file = "./public/upload/$date";
        if (!is_dir($file)) {
            mkdir($file, 0777, true);
        }
        $imagename = "./public/upload/$date/" . time() . $this->store['user_id'] . '.png';
        $font = './public/font/msyhbd.ttc';
        $red = '#35afd8';
        $white = '#ffffff';
        if ($condition == 0) {
            $image->open($path)->text($content, $font, 40, $red, \Think\Image::IMAGE_WATER_NORTHWEST, 55)
                    ->text($time, $font, 20, $white, \Think\Image::IMAGE_WATER_WEST, 75)
                    ->text($name, $font, 20, $red, \Think\Image::IMAGE_WATER_WEST, 40)
                    ->save($imagename);
        }
        $imagename = str_replace("./", "/", $imagename);
        return $imagename;
    }

    public function detail() {
        $coupon_id = (int) $_GET['coupon_id'];
        $u = D('User', 'Logic');
        $b = D('Barber', 'Logic');
        
            $ling = $this->coupon->getCouponUser($coupon_id);
            foreach ($ling as $k => $v) {
                if(!in_array($v['store_id'],$this->store_id)){
                    $this->_msg('非法操作！');
                }
                $user = $u->getUserById($v['client_id']);
                $ling[$k]['client_id'] = $user;
                $cou = $this->coupon->getHuiById($coupon_id);
                $ling[$k]['end_time'] = $cou['end_time'];
                $barber = $b->getBarber($v['barber_id']);
                $ling[$k]['barber_id'] = $barber;
            }
            $this->assign('ling', $ling);
        $count = $this->coupon->getCouponUserCount($coupon_id);
        $this->assign('count', $count);
        $this->assign('coupon_id', $coupon_id);
        $this->display('detail');
    }

    public function search() {
        $status = (int) $_GET['type'];
        $search = $_GET['Search'];
        $coupon_id = (int) $_GET['coupon_id'];
        $ling = $this->coupon->getCouponUser($coupon_id, $status, $search);
        $u = D('User', 'Logic');  
        $b=  D('Barber', 'Logic');
        foreach ($ling as $k => $v) {
            if(!in_array($v['store_id'],$this->store_id)){
                $this->_msg('_HAVE_NO_LEGAL_POWER_');
            }
            $user = $u->getUserById($v['client_id']);
            $ling[$k]['client_id'] = $user;
	        $cou = $this->coupon->getHuiById($coupon_id);
            $ling[$k]['end_time'] = $cou['end_time'];
            $barber = $b->getBarber($v['barber_id']);
            $ling[$k]['barber_id'] = $barber;
        }
        $count = $this->coupon->getCouponUserCount($coupon_id, $status, $search);
        $this->assign('count', $count);
        $this->assign('coupon_id', $coupon_id);
        $this->assign('type', (int) $_GET['type']);
        $this->assign('search', $search);
        $this->assign('ling', $ling);
        $this->display('detail');
    }

    public function append() {
        $start = (int) $_GET['start'];
        $coupon_id = (int) $_GET['coupon_id'];
        $status = (int) $_GET['type'];
        $search = $_GET['Search'];
        $ling = $this->coupon->getCouponUser($coupon_id, $status, $search, $start);
        $u = D('User', 'Logic');
	    $b=  D('Barber', 'Logic');
        foreach ($ling as $k => $v) {
            if(!in_array($v['store_id'],$this->store_id)){
                exit('false');
            }
            $user = $u->getUserById($v['client_id']);
            $ling[$k]['client_id'] = $user;
	        $ling[$k]['end_time'] = $cou['end_time'];
            $barber = $b->getBarber($v['barber_id']);
            $ling[$k]['barber_id'] = $barber;
        }
        if (count($ling) > 0) {
            exit(json_encode($ling));
        }
        exit('false');
    }

    //验证使用
    public function update() {
        $id = (int) $_GET['id'];
        $coupon_id = (int) $_GET['coupon_id'];
        $store = $this->coupon->getHuiById($coupon_id);
        if(!in_array($store['store_id'],$this->store_id)){
            $this->_msg('_HAVE_NO_LEGAL_POWER_');
        }
        $time = time();
        $type = array('status' => 1, 'use_time' => $time);
        $re = $this->coupon->update($id, $type);
        import('Memcachectr');
        $m = \Think\Memcachectr::create();
        $m->delete('ling');
        if ($re == false) {
            $this->_msg('_SYSTEM_ERROR_');
        } else {
            redirect("/home/coupon/detail?coupon_id=$coupon_id");
        }
    }

    //判断状态
    public function info() {
        $coupon_id = (int) $_GET['coupon_id'];
        $re = $this->coupon->getHuiById($coupon_id);
        if (in_array($re['store_id'],$this->store_id)) {
            if ($re['status'] == 1) {
                redirect("/home/coupon/peview?coupon_id=$coupon_id");
            } else {
                redirect("/home/coupon/create?coupon_id=$coupon_id");
            }
        } else {
            $this->_msg('_HAVE_NO_LEGAL_POWER_');
        }
    }

    //与活动有关的优惠劵查询
    public function action() {
        $num = $_GET['num'];
        $store_id = $_GET['store_id'];
        if(!in_array($store_id,$this->store_id)){
            $this->_msg('_HAVE_NO_LEGAL_POWER_');exit;
        }
        $re = $this->coupon->getCouponByAction($num, $store_id);
        $re = json_encode($re);
        echo $re;exit;
    }

    //优惠劵 指定发放
    public function receive(){
        import('Memcachectr');
        $m = \Think\Memcachectr::create();
        $re = $m->delete('ling');
        $mobile = $_GET['mobile'];
        $data['coupon_id'] = (int)$_GET['coupon_id_'];
        $u = new \Home\Logic\UserLogic();
        $c = new \Home\Logic\CouponLogic();
        $user = $u->getUserByAccount($mobile);
        if($user ==''){
            $re = $u->createUser($mobile);
            $data['client_id'] = $re;
        }else{
            $data['client_id'] = $user['id'];
        }
        $coupon = $c->getHuiById($data['coupon_id']);
        if(!in_array($coupon['store_id'],$this->store_id)){
            $this->_msg('_HAVE_NO_LEGAL_POWER_');exit;
        }
        
        $data['create_time'] = time();
        $data['store_id'] = $coupon['store_id'];
        $data['barber_id'] = (int)$_GET['barber_id'];
        if( $data['coupon_id']<1 ||
            $data['store_id']<1 ||
            $data['client_id']<1 ){
            exit('false');
        }
        
        //领取
        $num = (int)$_GET['num'];
        for($i=0;$i<$num;$i++){
            $data['number'] = $this->code();
            $s = $c->count($data['coupon_id'],$data);
            if($s == false){
                exit('false');//领取完
            }
        }
        if($s){   
            exit('true');
        }


    }
    //识别码
    public function code(){
        return date('ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
    }


}
